package kgc.crm.test;

import lombok.*;

//死锁:多个线程互相抱着对方需要的资源，然后形成僵持
public class DeadLock {
    public static void main(String[] args) {
        Makeup g1 = new Makeup(0,"小红");
        Makeup g2 = new Makeup(1,"小黄");
        g1.start();
        g2.start();
    }
}

//口红
class Kh {

}
//镜子
class Jz{

}
//化妆
@AllArgsConstructor
@NoArgsConstructor
@Data
class Makeup extends Thread {
    //需要的资源只有一份，用静态保证
    static Kh kh = new Kh();
     static Jz jz = new Jz();

    private int choice;//选择
    private String girlName;//使用化妆品的人


    @SneakyThrows
    @Override
    public void run() {
        makeup();
    }
//化妆，互相持有对方的锁，就是需要拿到对方的资源
    private void makeup() throws InterruptedException {
        if (choice == 0) { //如果选择0先拿口红，
            synchronized (kh) {//给口红添加同步锁
                System.out.println(this.girlName+"拿到了口红");
                Thread.sleep(1000);//一秒后再去拿镜子
                synchronized (jz) {
                    System.out.println(this.girlName+"拿镜子");
                }
            }
        }else {//第二个人
            synchronized (jz) {//给口红添加同步锁
                System.out.println(this.girlName+"拿镜子");
                Thread.sleep(2000);//一秒后再去拿镜子
                synchronized (kh) {
                    System.out.println(this.girlName+"拿口红");
                }
            }
        }
    }
}